// recipe.js
const app = getApp();

Page({
  data: {
    recipes: [],
    filteredRecipes: [],
    currentRecipe: {},
    activeCategory: 'all',
    showDetail: false,
    showSearch: false,
    searchKeyword: '',
    searchResults: [],
    hasMore: true,
    page: 1,
    pageSize: 10,
    isFavorite: false,
    categories: [
      { id: 'all', name: '全部', icon: 'all' },
      { id: 'breakfast', name: '早餐', icon: 'breakfast' },
      { id: 'lunch', name: '午餐', icon: 'lunch' },
      { id: 'dinner', name: '晚餐', icon: 'dinner' },
      { id: 'dessert', name: '甜品', icon: 'dessert' },
      { id: 'snack', name: '小吃', icon: 'snack' }
    ]
  },

  onLoad: function() {
    // 加载食谱数据
    this.loadRecipes();
    
    // 获取收藏列表
    this.loadFavorites();
  },

  onShow: function() {
    // 页面显示时刷新数据
    this.setData({
      page: 1,
      hasMore: true
    });
    this.loadRecipes(true);
  },

  // 加载食谱数据
  loadRecipes: function(refresh = false) {
    wx.showLoading({
      title: '加载中...',
    });
    
    // 这里应该调用API获取数据，现在使用模拟数据
    const mockRecipes = [
      {
        id: 1,
        title: '番茄炒蛋',
        imageUrl: '../../images/tomato-egg.png',
        category: '午餐',
        difficulty: '简单',
        cookTime: 20,
        likes: 1280,
        brief: '经典的家常菜，酸甜可口，营养丰富',
        description: '番茄炒蛋是一道非常经典的家常菜，酸甜可口，红黄相间，不仅外观诱人，而且营养丰富。番茄富含维生素C，鸡蛋含有丰富的蛋白质，两者搭配既美味又健康。',
        ingredients: [
          { name: '鸡蛋', quantity: '3个' },
          { name: '番茄', quantity: '2个' },
          { name: '食用油', quantity: '适量' },
          { name: '盐', quantity: '适量' },
          { name: '糖', quantity: '一小勺' }
        ],
        steps: [
          { description: '将鸡蛋打散，加入少许盐，搅拌均匀', imageUrl: '../../images/step1.png' },
          { description: '番茄洗净，切块备用', imageUrl: '../../images/step2.png' },
          { description: '热锅冷油，倒入蛋液炒至成型盛出', imageUrl: '../../images/step3.png' },
          { description: '锅中留底油，放入番茄块翻炒', imageUrl: '../../images/step4.png' },
          { description: '加入少许糖和盐调味，炒至番茄软烂', imageUrl: '../../images/step5.png' },
          { description: '倒入炒好的鸡蛋，翻炒均匀即可出锅', imageUrl: '../../images/step6.png' }
        ],
        tips: '1. 番茄最好选择熟透的，这样炒出来的口感更好\n2. 鸡蛋不要炒太老，保持嫩滑\n3. 可以根据个人口味调整糖的用量'
      },
      {
        id: 2,
        title: '清蒸鱼',
        imageUrl: '../../images/steamed-fish.png',
        category: '晚餐',
        difficulty: '中等',
        cookTime: 30,
        likes: 956,
        brief: '保留鱼肉鲜嫩，营养丰富的烹饪方式',
        description: '清蒸鱼是一种健康的烹饪方式，能够最大程度地保留鱼肉的鲜嫩和营养。鱼肉富含优质蛋白质和不饱和脂肪酸，对心血管健康有益。',
        ingredients: [
          { name: '鲈鱼', quantity: '1条(约500g)' },
          { name: '姜片', quantity: '5片' },
          { name: '葱丝', quantity: '适量' },
          { name: '料酒', quantity: '1勺' },
          { name: '生抽', quantity: '2勺' },
          { name: '食用油', quantity: '适量' }
        ],
        steps: [
          { description: '鱼处理干净，在两面划几刀，用料酒和盐腌制10分钟', imageUrl: '../../images/step1.png' },
          { description: '盘中铺上姜片，放上鱼，再在鱼身上撒些姜片和葱丝', imageUrl: '../../images/step2.png' },
          { description: '锅中水烧开后，放入鱼盘，大火蒸8-10分钟', imageUrl: '../../images/step3.png' },
          { description: '取出鱼盘，倒掉盘中的水', imageUrl: '../../images/step4.png' },
          { description: '将新的葱丝铺在鱼身上，淋上生抽', imageUrl: '../../images/step5.png' },
          { description: '锅中油烧热，浇在葱丝上，听到嗤嗤声即可', imageUrl: '../../images/step6.png' }
        ],
        tips: '1. 蒸鱼的时间要控制好，过长会导致鱼肉变老\n2. 浇油时油温要高，这样才能激发出葱的香味\n3. 可以根据个人口味加入少许香菜'
      },
      {
        id: 3,
        title: '水果沙拉',
        imageUrl: '../../images/fruit-salad.png',
        category: '甜品',
        difficulty: '简单',
        cookTime: 15,
        likes: 842,
        brief: '清爽健康的水果组合，适合夏季食用',
        description: '水果沙拉是一道清爽健康的甜品，富含维生素和纤维素，有助于消化和美容养颜。选择当季新鲜水果，搭配适量沙拉酱，简单又美味。',
        ingredients: [
          { name: '苹果', quantity: '1个' },
          { name: '香蕉', quantity: '1根' },
          { name: '草莓', quantity: '10颗' },
          { name: '猕猴桃', quantity: '1个' },
          { name: '酸奶', quantity: '200ml' },
          { name: '蜂蜜', quantity: '1勺' }
        ],
        steps: [
          { description: '将所有水果洗净切块', imageUrl: '../../images/step1.png' },
          { description: '草莓去蒂切块，猕猴桃去皮切块', imageUrl: '../../images/step2.png' },
          { description: '将切好的水果放入大碗中', imageUrl: '../../images/step3.png' },
          { description: '加入酸奶和蜂蜜', imageUrl: '../../images/step4.png' },
          { description: '轻轻拌匀，避免水果破碎', imageUrl: '../../images/step5.png' },
          { description: '装入漂亮的碗中即可食用', imageUrl: '../../images/step6.png' }
        ],
        tips: '1. 水果最好选择硬度适中的，避免过于软烂\n2. 可以根据个人口味选择不同的酸奶或沙拉酱\n3. 制作好的水果沙拉最好尽快食用，避免氧化变色'
      }
    ];
    
    setTimeout(() => {
      wx.hideLoading();
      
      if (refresh) {
        this.setData({
          recipes: mockRecipes,
          filteredRecipes: mockRecipes
        });
      } else {
        const newRecipes = [...this.data.recipes, ...mockRecipes];
        this.setData({
          recipes: newRecipes,
          filteredRecipes: newRecipes
        });
      }
      
      // 模拟数据加载完毕
      if (this.data.page > 2) {
        this.setData({
          hasMore: false
        });
      }
      
      // 筛选食谱
      this.filterRecipes();
    }, 1000);
  },

  // 加载收藏列表
  loadFavorites: function() {
    // 这里应该从本地存储或云端获取收藏数据
    const favorites = wx.getStorageSync('favorites') || [];
    this.setData({
      favorites: favorites
    });
  },

  // 筛选食谱
  filterRecipes: function() {
    let filtered = this.data.recipes;
    
    // 按分类筛选
    if (this.data.activeCategory !== 'all') {
      const categoryMap = {
        'breakfast': '早餐',
        'lunch': '午餐',
        'dinner': '晚餐',
        'dessert': '甜品',
        'snack': '小吃'
      };
      const categoryName = categoryMap[this.data.activeCategory];
      filtered = filtered.filter(recipe => recipe.category === categoryName);
    }
    
    this.setData({
      filteredRecipes: filtered
    });
  },

  // 选择分类
  selectCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      activeCategory: category
    });
    this.filterRecipes();
  },

  // 查看食谱详情
  viewRecipeDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    const recipe = this.data.recipes.find(r => r.id === id);
    
    if (recipe) {
      // 检查是否收藏
      const isFavorite = this.data.favorites && this.data.favorites.includes(id);
      
      this.setData({
        currentRecipe: recipe,
        showDetail: true,
        isFavorite: isFavorite
      });
    }
  },

  // 关闭详情页
  closeDetail: function() {
    this.setData({
      showDetail: false
    });
  },

  // 切换收藏状态
  toggleFavorite: function() {
    const recipeId = this.data.currentRecipe.id;
    let favorites = wx.getStorageSync('favorites') || [];
    let isFavorite = this.data.isFavorite;
    
    if (isFavorite) {
      // 取消收藏
      favorites = favorites.filter(id => id !== recipeId);
    } else {
      // 添加收藏
      favorites.push(recipeId);
    }
    
    // 保存到本地存储
    wx.setStorageSync('favorites', favorites);
    
    this.setData({
      isFavorite: !isFavorite,
      favorites: favorites
    });
    
    wx.showToast({
      title: isFavorite ? '取消收藏' : '收藏成功',
      icon: 'success',
      duration: 2000
    });
  },

  // 分享食谱
  shareRecipe: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 开始烹饪
  makeRecipe: function() {
    wx.showToast({
      title: '开始烹饪功能开发中',
      icon: 'none'
    });
  },

  // 打开搜索
  onSearch: function() {
    this.setData({
      showSearch: true,
      searchKeyword: '',
      searchResults: []
    });
  },

  // 取消搜索
  cancelSearch: function() {
    this.setData({
      showSearch: false,
      searchKeyword: '',
      searchResults: []
    });
  },

  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    
    // 实时搜索
    this.searchRecipes();
  },

  // 清空搜索
  clearSearch: function() {
    this.setData({
      searchKeyword: '',
      searchResults: []
    });
  },

  // 执行搜索
  doSearch: function() {
    this.searchRecipes();
  },

  // 搜索食谱
  searchRecipes: function() {
    const keyword = this.data.searchKeyword.toLowerCase().trim();
    
    if (!keyword) {
      this.setData({
        searchResults: []
      });
      return;
    }
    
    // 搜索食谱（标题、食材等）
    const results = this.data.recipes.filter(recipe => {
      return recipe.title.toLowerCase().includes(keyword) ||
             recipe.category.toLowerCase().includes(keyword) ||
             recipe.ingredients.some(ing => ing.name.toLowerCase().includes(keyword)) ||
             recipe.brief.toLowerCase().includes(keyword);
    });
    
    this.setData({
      searchResults: results
    });
  },

  // 加载更多
  loadMore: function() {
    if (!this.data.hasMore) return;
    
    this.setData({
      page: this.data.page + 1
    });
    
    this.loadRecipes();
  },

  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  },

  // 分享功能实现
  onShareAppMessage: function() {
    return {
      title: this.data.currentRecipe.title || '美食推荐',
      path: '/pages/recipe/recipe?id=' + this.data.currentRecipe.id,
      imageUrl: this.data.currentRecipe.imageUrl || '../../images/logo.png'
    };
  },

  onShareTimeline: function() {
    return {
      title: this.data.currentRecipe.title || '美食推荐',
      query: 'id=' + this.data.currentRecipe.id,
      imageUrl: this.data.currentRecipe.imageUrl || '../../images/logo.png'
    };
  }
})